using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using EPiAbstractions;
using EPiServer.Core;
using JoelAbrahamsson.Web.Common;
using JoelAbrahamsson.PageTypes;

namespace JoelAbrahamsson.Web.Controllers
{
    public class MainMenuController : Controller
    {
        private IDataFactoryFacade _dataFactoryFacade;

        public MainMenuController(IDataFactoryFacade dataFactoryFacade)
        {
            _dataFactoryFacade = dataFactoryFacade;
        }

        public ActionResult Menu()
        {
            List<MenuLink> menuLinks = new List<MenuLink>();
            
            MenuLink homeLink = new MenuLink
                {
                    Text = "Home",
                    RouteValues = new RouteValueDictionary(new
                       { 
                           controller = "Home"
                       })
                };
            menuLinks.Add(homeLink);

            MenuLink archiveLink = new MenuLink
            {
                Text = "Archive",
                RouteValues = new RouteValueDictionary(new
                    {
                        controller = "Archive",
                        action = "Index"
                    })
            };
            menuLinks.Add(archiveLink);

            IEnumerable<BasePageData> pagesToShowInMenu = _dataFactoryFacade.GetChildren(PageReference.StartPage)
                .Where(page => page.CheckPublishedStatus(PagePublishedStatus.Published) && page.VisibleInMenu && page is BasePageData)
                .Cast<BasePageData>();

            foreach (BasePageData page in pagesToShowInMenu)
            {
                MenuLink pageLink = new MenuLink
                {
                    Text = page.PageName,
                    RouteValues = new RouteValueDictionary(new
                    {
                        controller = page.ControllerName,
                        action = "Index",
                        slug = page.Slug
                    })
                };

                menuLinks.Add(pageLink);
            }

            return View(menuLinks);
        }

    }
}
